﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Interpolation2D
{
    class InterpolationEx
    {
        #region === private ===

        static private double L(double[] X, int j, double t)
        {
            double Y = 1;

            for (int i = 0; i < X.Length; i++)
            {
                if (i == j)
                    continue;

                Y *= (t - X[i]) / (X[j] - X[i]);
            }

            return Y;
        }

        #endregion

        static public double Lagrang(double[] X, double[] Y, double t)
        {
            double Yout = 0;

            for (int i = 0; i < X.Length; i++)
            {
                Yout += Y[i] * L(X, i, t);
            }

            return Yout;
        }

        static public double LinearTrend(double[] X, double[] Y, double t)
        {
            int count = X.Length;

            if (count == 1)
                return Y[0];

            double a11 = 0, a12 = 0, b1 = 0, b2 = 0;

            for (int i = 0; i < count; i++)
            {
                a11 += X[i] * X[i];
                a12 += X[i];
                b1 += X[i] * Y[i];
                b2 += Y[i];
            }

            double a21 = a12;
            double a22 = count;

            Matrix2D A = new Matrix2D(a11, a12, a21, a22);
            Vector2D b = new Vector2D(b1, b2);

            Vector2D vector = LinearSolver.Solve2x2(A, b);

            return vector.X * t + vector.Y;
        }
    }
}
